import { FormSchema, SchemaForm, SchemaFormRef } from "@/framework/components/core/schema-form";
import { FormDrawerProps, useDrawer } from "@/framework/components/core/drawer";
import { nextTick, ref } from "vue";

interface ShowDrawerProps<T = Recordable> {
  drawerProps: FormDrawerProps<T>;
  formSchema: FormSchema;
}

export function useFormDrawer<T extends Recordable>() {
  const { show, hide } = useDrawer();

  const showDrawer = async <P extends T>({ drawerProps, formSchema }: ShowDrawerProps<P>) => {
    const formRef = ref<SchemaFormRef>();

    const onCancel = async () => {
      formRef.value?.resetFields();
      hide();
    };

    const onOk = async () => {
      const values = (formRef.value?.formModel || {}) as any;
      try {
        await formRef.value?.validate();
        let isClose = await drawerProps?.onFinish?.({ ...values }, formRef);
        if(isClose){
          formRef.value?.resetFields();
          return Promise.resolve(true);
        }
      } catch (error) {
        drawerProps?.onFail?.({ ...values });
        return Promise.reject(error);
      }
    };
    await show({
      showOkBtn: true,
      showFooter: true,
      showCancelBtn: true,
      okText: "确定",
      cancelText: "取消",
      destroyOnClose: true,
      ...drawerProps,
      content: () => <SchemaForm ref={formRef} formSchema={formSchema}></SchemaForm>,
      closeFunc: onCancel,
      okFunc: onOk
    });

    await nextTick();
  };
  return { showDrawer };
}
